package com.example.mvc.controller;

import com.example.mvc.bean.User;
import com.example.mvc.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2. 调用service查询
        User loginUser = userService.login(username, password);
        //3. 判断
        if (loginUser!=null){//如果不为空说明用户是存在即用户名和密码是正确的
            //4.报错用户信息到session
            HttpSession session = req.getSession();
            session.setAttribute("user",loginUser);

            //5.跳转到查询所有
            String contextPath = req.getContextPath();
            resp.sendRedirect(contextPath+"/selectAllServlet");
        }else {
            // 登录失败,

            // 存储错误信息到request
            req.setAttribute("login_msg","用户名或密码错误");

            // 跳转到login.jsp
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }



    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
